package net.chrisrichardson.ec2deployer.cluster

import groovy.xml.MarkupBuilder
import net.chrisrichardson.ec2deployer.applications.DirectorySnapshot

public class ClusterCheckpoint {
  Map<String, Object> cloneState
  ClusterSpec clonedClusterSpec

  ClusterCheckpoint(Map<String, Object> cloneState, ClusterSpec clonedClusterSpec) {
    this.cloneState = cloneState
    this.clonedClusterSpec = clonedClusterSpec
  }

  void writeXmlToFile(File checkpointFile) {
    checkpointFile.withPrintWriter {pw ->
      toXml(pw)
    }
  }

  void toXml(PrintWriter pw) {
    def builder = new MarkupBuilder(pw)
    builder.checkpoint {
      cloneState {
        for (Object element in cloneState.entrySet()) {
          def key = element.key
          def value = element.value
          if (value instanceof String || value instanceof GString)
            "${key}"(value)
          else if (value instanceof DirectorySnapshot)
            "${key}" {
              directorySnapshot {
                directory(value.directory)
                s3Path (value.s3Path)
              }
            }
          else
            throw new UnsupportedOperationException("Dont know what to do with: " + value)
        }
      }

      clusterSpec {
        new ClusterDefinitionManager().writeProperties owner, clonedClusterSpec
      }
    }
  }
}